<template>
  <client-only>
    <FormDialog :formOption="formOption" :form="form" :rule="rule" ref="dialogRef" :reload="reload"/>
  </client-only>
</template>

<script setup lang="ts">
import FormDialog from "~/components/common/FormDialog.vue";
import {
  useApi
} from "~/composeables";
import {FormFieldType, FormOption} from "~/models/data/form";
import BookCategoryCache from "~/store/booksvr/bookCategoryCache";

const props = defineProps<{
  reload: Function,
}>();


const api = useApi();

const dialogRef = ref<any>(null);

const onSubmit = (model: any) => {
  api.systemDepartmentApi.update(model)
    .then(res => {
      if (res.success) {
        ElMessage.success("提交数据成功！");
        forceReload();
      } else {
        ElMessage.error("数据提交失败,请重新尝试！");
      }
    })
    .catch(err => {
      console.error(err);
      ElMessage.error("数据提交失败");
    })
}

const formOption = ref<FormOption>({
  title: '录入书籍分类信息',
  width: 480,
  labelWidth: 120,
  fieldList: [
    {
      fieldName: 'name',
      verboseName: '分类名称',
      fieldType: FormFieldType.input,
    },
    {
      fieldName: 'description',
      verboseName: '描述信息',
      fieldType: FormFieldType.textarea,
    },
    {
      fieldName: 'parentId',
      verboseName: '上级分类',
      fieldType: FormFieldType.cascader,
      selectSource: BookCategoryCache.bookCategoryTreeSelectSource,
      isMultiSelect: false,
      needHideSelf: true,
    }
  ],
  submitFunc: onSubmit,
});

const form: any = ref({
  name : "",
  description : "",
  parentId : null,
});

const rule = ref([]);

const open = (data : any) => {
  dialogRef.value.open(JSON.parse(JSON.stringify(data)));
}

const close = () => {
  dialogRef.value.close();
}

const forceReload = ()=>{
  window.location.reload()
}

defineExpose({
  open,
  close,
  dialogRef,
})

</script>